package com.sjy.imagepicker.adapter;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.github.chrisbanes.photoview.PhotoView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhang on 2017/4/9.
 */

public class ImageViewerAdapter extends PagerAdapter {
    private List<PhotoView> cache;
    private List<String> mImgList;

    public ImageViewerAdapter(List<String> imgList) {
        cache = new ArrayList<PhotoView>();
        this.mImgList = imgList;
    }

    @Override
    public int getCount() {
        return mImgList == null?0:mImgList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {

        return view == object;
    }

    public String getItem(int position) {
        return mImgList.get(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (cache.isEmpty()) {
            PhotoView photoView = new PhotoView(container.getContext());
            //photoView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            cache.add(photoView);
        }
        PhotoView photoView = cache.remove(0);

        RequestOptions options = new RequestOptions()
                .priority(Priority.HIGH);
        Glide.with(container.getContext()).load(getItem(position)).apply(options).into(photoView);
        container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        return photoView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        PhotoView photoView = (PhotoView) object;
        cache.add(photoView);
        container.removeView(photoView);
    }
}
